import {
  join,
  dirname
} from "path";
import {
  builtinModules
} from "module";
import defineConfig from "./defineConfig";
import pkg from "../package.json";
import _plugins from "./plugins";
import AutoImport from "unplugin-auto-import/vite";
import rollupPluginNode from "./rollup-plugin-node";

const production = process.env.NODE_ENV === "production";
const ROOT = dirname(__dirname);
const external = ["node-gyp-build", "electron", ...builtinModules];
const plugins = [
  ..._plugins,
  AutoImport({
    include: [/\.[tj]s?$/, /\.coffee$/],
    imports: [{
      electron: ["BrowserWindow"]
    }],
  }),
];

if (production) {
  plugins.push(rollupPluginNode);
} else {
  external.push("@rmw/node-window-manager");
}

export default defineConfig({
  plugins,
  esbuild: {
    target: "node"
  },
  mode: process.env.NODE_ENV,
  root: join(ROOT, "src/main"),
  build: {
    outDir: "m",
    lib: {
      entry: "m.coffee",
      formats: ["cjs"]
    },
    sourcemap: production ? false : "inline",
    minify: production,
    emptyOutDir: true,
    rollupOptions: {
      external,
      output: {
        entryFileNames: "[name].cjs"
      }
    },
  },
});
